package server

import (
	"context"
	"github.com/asim/go-micro/plugins/client/grpc/v4"
	"github.com/asim/go-micro/plugins/registry/etcd/v4"
	"github.com/asim/go-micro/plugins/wrapper/select/roundrobin/v4"
	"go-micro.dev/v4"
	"go-micro.dev/v4/client"
	"go-micro.dev/v4/registry"
	log "maya-service/collector/logger"
	"maya-service/config"
	"maya-service/event"
	grpcServer "maya-service/server/grpc"
	"maya-service/server/grpc/middleware"
	webServer "maya-service/server/web"
	// example: other server
	// exampleServer "maya-service-layout/server/example_server"
)

func Init() func() {
	config.MicroService = micro.NewService()

	options := []micro.Option{
		micro.AfterStart(AfterStart),
		micro.AfterStop(AfterExit),
		// client trace wrapper
		// choose you needed wrapper
		webServer.Init(),
		// Add other server here
		// example:
		// exampleServer.Init(),
	}

	if config.EtcdAddr != "" {
		options = append(options, micro.Registry(etcd.NewRegistry(registry.Addrs(config.EtcdAddr))))
		options = append(options, micro.Client(grpc.NewClient(client.WrapCall(middleware.ClientTraceWrapper()))))
		options = append(options, micro.WrapClient(roundrobin.NewClientWrapper()))
		options = append(options, grpcServer.Init())
	}

	config.MicroService.Init(options...)
	return func() {}
}

func AfterStart() error {
	log.Info("finished to init all component")
	return nil
}

func AfterExit() error {
	event.Publish(context.Background(), event.EventExit, nil)
	log.Info("server shutdown!")
	return nil
}
